/**
 * 画笔选择
 */
var Draw = {
	init: function() {
		map.addInteraction(this.Point1);
		this.Point1.setActive(false);
		this.setEvents("Point1");
		map.addInteraction(this.Point2);
		this.Point2.setActive(false);
		this.setEvents("Point2");
		map.addInteraction(this.Range);
		this.Range.setActive(false);
		this.setEvents("Range");
		map.addInteraction(this.LineString1);
		this.LineString1.setActive(false);
		this.setEvents("LineString1");
		map.addInteraction(this.LineString2);
		this.LineString2.setActive(false);
		this.setEvents("LineString2");
		map.addInteraction(this.Measure);
		this.Measure.setActive(false);
		this.setEvents("Measure");
		map.addInteraction(this.Polygon1);
		this.Polygon1.setActive(false);
		this.setEvents("Polygon1");
		/*map.addInteraction(this.GeometryCollection);
		this.GeometryCollection.setActive(false);*/
	},
	Point1: new ol.interaction.Draw({
		source: source,
		type: 'Point',
		style: function(feature, resolution) {
			return styles["Point1"];
		}
	}),
	Point2: new ol.interaction.Draw({
		source: source,
		type: 'Point',
		style: function(feature, resolution) {
			return styles["Point2"];
		}
	}),
	Range: new ol.interaction.Draw({
		source: sourceLayer,
		type: 'LineString',
		style: [new ol.style.Style({
			stroke: new ol.style.Stroke({
				color: '#666',
				width: 4
			}),
			zIndex: 1
		}), new ol.style.Style({
			stroke: new ol.style.Stroke({
				color: 'white',
				width: 2,
				lineDash: [10, 3]
			}),
			zIndex: 2
		})]
	}),
	LineString1: new ol.interaction.Draw({
		source: source,
		type: 'LineString',
		style: function(feature, resolution) {
			return styles["LineString1"];
		}
	}),
	LineString2: new ol.interaction.Draw({
		source: source,
		type: 'LineString',
		style: function(feature, resolution) {
			return styles["LineString2"];
		}
	}),
	Measure: new ol.interaction.Draw({
		source: sourceLayer,
		type: 'Polygon',
		style: function(feature, resolution) {
			return styles["Measure"];
		}
	}),
	Polygon1: new ol.interaction.Draw({
		source: source,
		type: 'Polygon',
		style: function(feature, resolution) {
			return styles["Polygon1"];
		}
	}),
	setEvents: function(activeType) {
		//设置绘画监听事件
		var listener;
		this[activeType].on('drawstart',
			function(evt) {
				//取消鼠标双击放大事件
				Draw.setInteraction(false);
				//初始化存储
				geomFeature = new Array();
				sketch = evt.feature;
				geomFeature.push(sketch);
				//设置feature的type属性
				sketch.set("type", type);
				if (type == "Range" || type == "Measure") {
					var tooltipCoord = evt.coordinate;
					listener = sketch.getGeometry().on('change', function(evt) {
						var geom = evt.target;
						var output;
						if (geom instanceof ol.geom.Polygon) {
							output = MapUtil.formatArea((geom));
							tooltipCoord = geom.getInteriorPoint().getCoordinates();
						} else if (geom instanceof ol.geom.LineString) {
							output = MapUtil.formatLength((geom));
							tooltipCoord = geom.getLastCoordinate();
						}
						measureTooltipElement.innerHTML = output;
						measureTooltip.setPosition(tooltipCoord);
					});
				}
			}, this);
		this[activeType].on('drawend',
			function(evt) {
				if (type == "Range") {
					tempTooltipElement.className = 'tooltip tooltip-static';
					tempTooltip.setOffset([0, -7]);
					map.removeOverlay(measureTooltip);
					//向collection中追加节点
					var len = collection.push(geomFeature) - 1;
					evt.feature.set("location", len);
					tempTooltipElement.innerHTML += "<span class='glyphicon glyphicon-remove' aria-hidden='true' style='cursor: pointer;' onclick='MapUtil.removeFeature(" + len + ");'></span>";
				}
				if (type == "Measure") {
					measureTooltipElement.className = 'tooltip tooltip-static';
					measureTooltip.setOffset([0, -7]);
					geomFeature.push(measureTooltip);
					//向collection中追加节点
					var len = collection.push(geomFeature) - 1;
					evt.feature.set("location", len);
					measureTooltipElement.innerHTML += "<span class='glyphicon glyphicon-remove' aria-hidden='true' style='cursor: pointer;' onclick='MapUtil.removeFeature(" + len + ");'></span>";
				}
				//重置画笔
				$("#" + this.previousType).click();
				// unset sketch
				sketch = null;
				MapUtil.createMeasureTooltip();
				setTimeout("Draw.setInteraction(true)", 1000);
			}, this);
			this[activeType].handleUpEvent_ = function(event) {
				//新增捕捉功能
				var start = event.coordinate;
				var wo_extent = MapUtil.calExtent(start,50);
				if (this.mode_ === ol.interaction.DrawMode.LINE_STRING) {
					source.forEachFeatureIntersectingExtent(wo_extent, function(feature) {
						if (feature.getGeometry() instanceof ol.geom.Point) {
							MapUtil.flash(feature);
							event.coordinate = feature.getGeometry().getLastCoordinate();
							return;
						}
					});
				} else if (this.mode_ === ol.interaction.DrawMode.POINT) {
					source.forEachFeatureIntersectingExtent(wo_extent, function(feature) {
						if (feature.getGeometry() instanceof ol.geom.LineString) {
							event.coordinate = feature.getGeometry().getLastCoordinate();
							return;
						}
					});
				}
				//结束
				this.freehand_ = false;
				var downPx = this.downPx_;
				var clickPx = event.pixel;
				var dx = downPx[0] - clickPx[0];
				var dy = downPx[1] - clickPx[1];
				var squaredDistance = dx * dx + dy * dy;
				var pass = true;
				if (squaredDistance <= this.squaredClickTolerance_) {
					this.handlePointerMove_(event);
					if (goog.isNull(this.finishCoordinate_)) {
						this.startDrawing_(event);
						if (this.mode_ === ol.interaction.DrawMode.POINT) {
							this.finishDrawing();
						}
					} else if (this.mode_ === ol.interaction.DrawMode.CIRCLE) {
						this.finishDrawing();
					} else if (this.atFinish_(event)) {
						this.finishDrawing();
					} else {
						this.addToDrawing_(event);
					}
					pass = false;
				}
				return pass;
			};
			this[activeType].__proto__.modifyDrawing_ = function(event) {
				var coordinate = event.coordinate;
				var geometry = this.sketchFeature_.getGeometry();
				goog.asserts.assertInstanceof(geometry, ol.geom.SimpleGeometry,
					'geometry should be ol.geom.SimpleGeometry or subclass');
				var coordinates, last;
				if (this.mode_ === ol.interaction.DrawMode.POINT) {
					last = this.sketchCoords_;
				} else if (this.mode_ === ol.interaction.DrawMode.POLYGON) {
					coordinates = this.sketchCoords_[0];
					last = coordinates[coordinates.length - 1];
					if (this.atFinish_(event)) {
						// snap to finish
						coordinate = this.finishCoordinate_.slice();
					}
				} else {
					coordinates = this.sketchCoords_;
					last = coordinates[coordinates.length - 1];
				}
				//新增画直线逻辑
				if (this.mode_ != ol.interaction.DrawMode.POINT && ol.events.condition.shiftKeyOnly(event)) {
					var geomLast = coordinates[coordinates.length - 2];
					var angle = Math.atan((coordinate[1] - geomLast[1]) / (coordinate[0] - geomLast[0]));
					var angleabs = Math.abs(angle);
					if (angleabs <= Math.PI / 6) {
						coordinate = [coordinate[0], geomLast[1]];
					} else if (Math.PI / 6 < angleabs && angleabs < (Math.PI / 3)) {
						if (angle > 0) {
							var x = (geomLast[0] - geomLast[1] + coordinate[0] + coordinate[1]) / 2;
							var y = (geomLast[1] - geomLast[0] + coordinate[0] + coordinate[1]) / 2;
						} else {
							var x = (geomLast[0] + geomLast[1] + coordinate[0] - coordinate[1]) / 2;
							var y = (geomLast[1] + geomLast[0] + coordinate[1] - coordinate[0]) / 2;
						}
						coordinate = [x, y];
					} else if (angleabs >= Math.PI / 3) {
						coordinate = [geomLast[0], coordinate[1]];
					}
				}
				//结束
				last[0] = coordinate[0];
				last[1] = coordinate[1];
				goog.asserts.assert(!goog.isNull(this.sketchCoords_),
					'sketchCoords_ must not be null');
				this.geometryFunction_(this.sketchCoords_, geometry);
				if (!goog.isNull(this.sketchPoint_)) {
					var sketchPointGeom = this.sketchPoint_.getGeometry();
					goog.asserts.assertInstanceof(sketchPointGeom, ol.geom.Point,
						'sketchPointGeom should be an ol.geom.Point');
					sketchPointGeom.setCoordinates(coordinate);
				}
				var sketchLineGeom;
				if (geometry instanceof ol.geom.Polygon &&
					this.mode_ !== ol.interaction.DrawMode.POLYGON) {
					if (goog.isNull(this.sketchLine_)) {
						this.sketchLine_ = new ol.Feature(new ol.geom.LineString(null));
					}
					var ring = geometry.getLinearRing(0);
					sketchLineGeom = this.sketchLine_.getGeometry();
					goog.asserts.assertInstanceof(sketchLineGeom, ol.geom.LineString,
						'sketchLineGeom must be an ol.geom.LineString');
					sketchLineGeom.setFlatCoordinates(
						ring.getLayout(), ring.getFlatCoordinates());
				} else if (!goog.isNull(this.sketchLineCoords_)) {
					sketchLineGeom = this.sketchLine_.getGeometry();
					goog.asserts.assertInstanceof(sketchLineGeom, ol.geom.LineString,
						'sketchLineGeom must be an ol.geom.LineString');
					sketchLineGeom.setCoordinates(this.sketchLineCoords_);
				}
				this.updateSketchFeatures_();
			};
			this[activeType].handleMoveEvent_ = function(event){
				var start = event.coordinate;
				var wo_extent = MapUtil.calExtent(start,50);
				if (this.mode_ === ol.interaction.DrawMode.LINE_STRING) {
					source.forEachFeatureIntersectingExtent(wo_extent, function(feature) {
						if (feature.getGeometry() instanceof ol.geom.Point) {
							MapUtil.flash(feature);
							return;
						}
					});
				}
			};
	},
	setActive: function(active) {
		//激活画笔
		if (active) {
			this[type].setActive(true);
			this.previousType = type;
			//去除图层的鼠标事件
			$(".ol-overlay-container").addClass("overlay");
			//重置样式
			$("#" + this.previousType).find(".link").css("background-image", "url(img/bg-item-2x-1.png)");
		} else {
			//重置样式
			if (this.previousType) {
				$("#" + this.previousType).find(".link").css("background-image", "url(img/bg-item-2x.png)");
				this[this.previousType].setActive(false);
			}
			this.previousType = null;
			//添加图层鼠标事件
			$(".ol-overlay-container").removeClass("overlay");
		}
	},
	//取消鼠标双击放大事件
	setInteraction: function(active) {
		var interactions = map.getInteractions();
		interactions.forEach(function(element, index, array) {
			if (element instanceof ol.interaction.DoubleClickZoom) {
				element.setActive(active);
			}
		});
	},
	getActive: function() {
		return this.previousType ? this[this.previousType].getActive() : false;
	}
};


/**
 * 定位   路线高亮     坐标高亮
 */
var MapUtil = {
	//
	wgs84Sphere: new ol.Sphere(6378137),
	/**
	 * 定位feature
	 * @param {Object} feature
	 */
	location: function(feature) {
		var geom = feature.getGeometry();
		var duration = 2000;
		var start = +new Date();
		var pan = ol.animation.pan({
			duration: duration,
			start: start,
			source: view.getCenter()
		});
		var bounce = ol.animation.bounce({
			duration: duration,
			resolution: 4 * view.getResolution(),
			start: start
		});
		var zoom = ol.animation.zoom({
			resolution: view.getResolution()
		});
		map.beforeRender(pan, bounce, zoom);
		if (view.getZoom() < maxZoom) {
			view.setZoom(view.getZoom() + 1);
		}
		if (geom instanceof ol.geom.Point) {
			view.setCenter(geom.getFirstCoordinate());
		} else if (geom instanceof ol.geom.LineString) {
			var coor = [];
			console.log(geom.getFirstCoordinate());
			coor[0] = (geom.getFirstCoordinate()[0] + geom.getLastCoordinate()[0]) / 2;
			coor[1] = (geom.getFirstCoordinate()[1] + geom.getLastCoordinate()[1]) / 2;
			view.setCenter(coor);
		} else if (geom instanceof ol.geom.Polygon) {
			view.setCenter(geom.getInteriorPoint().getFirstCoordinate());
		}
	},
	/**
	 * 线条高亮
	 * ol.feature
	 * @param {Object} linStrig
	 */
	lineHight: function(linStrig) {
		var newFeature = linStrig.clone();
		newFeature.setStyle(new ol.style.Style({
			stroke: new ol.style.Stroke({
				color: 'rgba(255, 0, 0, ' + 0.3 + ')',
				width: 10,
				zIndex: 0
			})
		}));
		var interval = setInterval(function() {
			source.addFeature(newFeature);
			setTimeout(function() {
				source.removeFeature(newFeature);
			}, 200);
		}, 500);
		setTimeout(function() {
			clearInterval(interval);
		}, 7000);
	},
	/**
	 * 点高亮
	 * @param {Object} point
	 */
	pointHight: function(point) {
		var interval = setInterval(function() {
			source.removeFeature(point);
			setTimeout(function() {
				source.addFeature(point);
			}, 200);
		}, 500);
		setTimeout(function() {
			clearInterval(interval);
		}, 7000);
	},
	/**
	 * 点高亮2
	 */
	flash: function(feature) {
		var start = new Date().getTime();
		var listenerKey;
		var duration = 3000;
		function animate(event) {
			var vectorContext = event.vectorContext;
			var frameState = event.frameState;
			var flashGeom = feature.getGeometry().clone();
			var elapsed = frameState.time - start;
			var elapsedRatio = elapsed / duration;
			// radius will be 5 at start and 30 at end.
			var radius = ol.easing.easeOut(elapsedRatio) * 25 + 5;
			var opacity = ol.easing.easeOut(1 - elapsedRatio);

			var flashStyle = new ol.style.Circle({
				radius: radius,
				snapToPixel: false,
				stroke: new ol.style.Stroke({
					color: 'rgba(255, 0, 0, ' + opacity + ')',
					width: 1,
					opacity: opacity
				})
			});

			vectorContext.setImageStyle(flashStyle);
			vectorContext.drawPointGeometry(flashGeom, null);
			if (elapsed > duration) {
				ol.Observable.unByKey(listenerKey);
				return;
			}
			// tell OL3 to continue postcompose animation
			frameState.animate = true;
		}
		listenerKey = map.on('postcompose', animate);
	},
	/**
	 * 计算长度
	 */
	formatLength: function(line) {
		var length;
		var coordinates = line.getCoordinates();
		length = 0;
		var sourceProj = map.getView().getProjection();
		for (var i = 0, ii = coordinates.length - 1; i < ii; ++i) {
			var c1 = ol.proj.transform(coordinates[i], sourceProj, 'EPSG:4326');
			var c2 = ol.proj.transform(coordinates[i + 1], sourceProj, 'EPSG:4326');
			length += this.wgs84Sphere.haversineDistance(c1, c2);
		}
		var output;
		if (length > 100) {
			output = (Math.round(length / 1000 * 100) / 100) +
				' ' + 'km';
		} else {
			output = (Math.round(length * 100) / 100) +
				' ' + 'm';
		}
		return output;
	},
	/**
	 * 计算面积
	 */
	formatArea: function(polygon) {
		var area;
		var sourceProj = map.getView().getProjection();
		var geom = /** @type {ol.geom.Polygon} */ (polygon.clone().transform(
			sourceProj, 'EPSG:4326'));
		var coordinates = geom.getLinearRing(0).getCoordinates();
		area = Math.abs(this.wgs84Sphere.geodesicArea(coordinates));
		var output;
		if (area > 10000) {
			output = (Math.round(area / 1000000 * 100) / 100) +
				' ' + 'km<sup>2</sup>';
		} else {
			output = (Math.round(area * 100) / 100) +
				' ' + 'm<sup>2</sup>';
		}
		return output;
	},
	/**
	 * 弹出提示图层
	 */
	createHelpTooltip: function() {
		helpTooltipElement = document.createElement('div');
		helpTooltipElement.className = 'tooltip hidden';
		helpTooltip = new ol.Overlay({
			element: helpTooltipElement,
			offset: [15, 0],
			positioning: 'center-left'
		});
		map.addOverlay(helpTooltip);
	},
	/**
	 * 测距和侧面积时弹出的临时显示图层
	 */
	createMeasureTooltip: function() {
		measureTooltipElement = document.createElement('div');
		measureTooltipElement.className = 'tooltip tooltip-measure';
		measureTooltip = new ol.Overlay({
			element: measureTooltipElement,
			offset: [0, -15],
			positioning: 'bottom-center'
		});
		map.addOverlay(measureTooltip);
	},
	/**
	 * 测距时创建路径节点图层
	 */
	createTempTooltip: function() {
		tempTooltipElement = document.createElement('div');
		tempTooltipElement.className = 'tooltip tooltip-measure';
		tempTooltip = new ol.Overlay({
			element: tempTooltipElement,
			offset: [0, -15],
			positioning: 'bottom-center'
		});
		map.addOverlay(tempTooltip);
	},
	/**
	 * 创建标注层
	 */
	createTagTooltip: function() {
		tagTooltipElement = document.getElementById('test').cloneNode(true);
		tagTooltip = new ol.Overlay({
			element: tagTooltipElement,
			offset: [0, -15],
			positioning: 'bottom-center'
		});
		map.addOverlay(tagTooltip);
	},
	/**
	 * 创建删除提示框
	 */
	createOperateTooltip: function() {
		operateTooltipElement = document.getElementById('operate').cloneNode(true);
		operateTooltip = new ol.Overlay({
			element: operateTooltipElement,
			offset: [0, -15],
			positioning: 'bottom-center'
		});
		map.addOverlay(operateTooltip);
	},
	/**
	 * 删除与测距相关的数据
	 * @param {Object} feature
	 * @param {Object} circle
	 */
	removeFeature: function(index) {
		var temp = collection[index];
		for (var i = 0; i < temp.length; i++) {
			try {
				if (temp[i] instanceof ol.Feature) {
					sourceLayer.removeFeature(temp[i]);
				} else {
					map.removeOverlay(temp[i]);
				}
			} catch (e) {}
		}
	},
	/**
	 * 重置按钮
	 * @param {Object} handleId
	 */
	testType: function(handleId) {
		$.each(sameType, function(key, value) {
			if (value) {
				$("#" + key).click();
				sameType[key] = false;
			}
		});
		sameType[handleId] = true;
	},
	/**
	 * 容差范围计算 
	 */
	calExtent: function(start,wo_tolerance){
		var wo_start_meter = ol.proj.fromLonLat(start);
		var wo_extent = ol.proj.transformExtent([wo_start_meter[0] - wo_tolerance, wo_start_meter[1] - wo_tolerance, wo_start_meter[0] + wo_tolerance, wo_start_meter[1] + wo_tolerance], "EPSG:3857", "EPSG:4326");
		return wo_extent;
	}
	
};
/**
 * 生成图形样式选择,zIndex 从2开始
 */
var styles = {
	'Point1': [new ol.style.Style({
		image: new ol.style.Icon({
			opacity: 0.95,
			src: 'img/u234.png'
		}),
		zIndex: 2
	})],
	'Point2': [new ol.style.Style({
		image: new ol.style.Icon( /** @type {olx.style.IconOptions} */ {
			opacity: 0.95,
			src: 'img/u304.png'
		}),
		zIndex: 2
	})],
	'Range': [new ol.style.Style({
		stroke: new ol.style.Stroke({
			color: '#666',
			width: 4
		}),
		zIndex: 1
	}), new ol.style.Style({
		stroke: new ol.style.Stroke({
			color: 'white',
			width: 2,
			lineDash: [10, 3]
		}),
		zIndex: 2
	}), new ol.style.Style({
		image: new ol.style.Circle({
			radius: 3,
			stroke: new ol.style.Stroke({
				color: 'red',
				width: 1
			})
		}),
		geometry: function(feature) {
			var coordinates = feature.getGeometry().getCoordinates();
			var circle = new ol.Feature(new ol.geom.MultiPoint(coordinates));
			//向collection中追加节点
			collection[feature.get("location")].push(circle);
			return circle.getGeometry();
		}
	})],
	'LineString1': [new ol.style.Style({
		stroke: new ol.style.Stroke({
			color: '#666',
			width: 3
		}),
		zIndex: 2
	}), new ol.style.Style({
		stroke: new ol.style.Stroke({
			color: 'white',
			width: 3,
			lineDash: [10, 20]
		}),
		zIndex: 2
	})],
	'LineString2': [new ol.style.Style({
		stroke: new ol.style.Stroke({
			color: 'green',
			width: 4
		}),
		zIndex: 2
	})],
	'Polygon1': [new ol.style.Style({
		stroke: new ol.style.Stroke({
			color: 'green',
			width: 1
		}),
		fill: new ol.style.Fill({
			color: 'rgba(0, 0, 255, 0.1)'
		})
	})],
	'Measure': [new ol.style.Style({
		stroke: new ol.style.Stroke({
			color: 'blue',
			lineDash: [4],
			width: 3
		}),
		fill: new ol.style.Fill({
			color: 'rgba(0, 0, 255, 0.1)'
		})
	})],
	'GeometryCollection': [new ol.style.Style({
		stroke: new ol.style.Stroke({
			color: 'magenta',
			width: 2
		}),
		fill: new ol.style.Fill({
			color: 'magenta'
		}),
		image: new ol.style.Circle({
			radius: 15,
			fill: null,
			stroke: new ol.style.Stroke({
				color: 'magenta'
			})
		}),
		zIndex: 2
	})]
};